#include "user_service.h"
#include "context.h"
#include "streamdata.h"
#include "log.h"
#include "1300_user_info.pb.h"


static bool __init__ = UserService::Instance()->Init();

bool UserService::Init()
{
    Ctx.msg_router.BindMsg(client_proto::UISMI_USERBASIC_GET_INFO_RESP, std::bind(&UserService::OnUserinfoGet, this, std::placeholders::_1));
    return true;
}

bool UserService::HandleGetUserinfo(const std::uint32_t& uid, std::string&& trans, Sence sence)
{
    StreamData stream_data;
    StreamDataWriter write(stream_data);
    write.Write<Sence>(sence);
    write.WriteString(trans);

    client_proto::GetUserBasicInfoReq req;
    req.set_user_id(uid);
    req.set_trans(std::move(stream_data.Data()));
    Ctx.host->MtSendtoSrv(client_proto::UISMI_USERBASIC_GET_INFO_REQ, SERVER_TYPE_USERINFO, &req, 0);
    return true;
}

void UserService::OnUserinfoGet(MsgData&& data)
{
    do
    {
        client_proto::GetUserBasicInfoResp resp;
        if (!resp.ParseFromArray(data.data.c_str(), data.data.size()))
        {
            log_error("parser client_proto::GetUserBasicInfoResp failed, stype:%d,svid:%d,uuid:%d", data.svtype, data.svid, data.uuid);
            break;
        }

        StreamData stream_data(std::move(*resp.mutable_trans()));
        StreamDataReader reader(stream_data);
        Sence sence = reader.Read<Sence>();
        std::string trans = reader.ReadString();

        try
        {
            auto it = m_userinfo_get_listen.find(sence);
            if (it == m_userinfo_get_listen.end())
            {
                log_warning("sence:%d not listen", sence);
                return;
            }
            it->second(resp);
        }
        catch(const std::exception& e)
        {
            log_error("catch exception:%s, sence:%d, stype:%d,svid:%d,uuid:%d,msg:%s", e.what(), sence, data.svtype, data.svid, data.uuid, resp.ShortDebugString().c_str());
        }
        catch(...)
        {
            log_error("catch unknown exception, sence:%d, stype:%d,svid:%d,uuid:%d,msg:%s", sence, data.svtype, data.svid, data.uuid, resp.ShortDebugString().c_str());
        }
    } while(false);
}



